const { promisify } = require("util");
const path = require("path");

const download = promisify(require("download-git-repo"));
const open = require("open");

const { vueRepo } = require("../config/repo-config");
const { commandSpan } = require("../untils/termin");
const { compile, writeToFile, createDirSync } = require("../untils/utils");

/**
 * 创建项目
 * @param {String} project 项目名
 */
const createProjectAction = async (project) => {
  console.log("正在创建项目,请稍后...");

  // 克隆项目
  await download(vueRepo, project, { clone: true });

  const command = process.platform === "win32" ? "npm.cmd" : "npm";

  // 安装项目依赖
  console.log("正在安装依赖,请稍后...");
  await commandSpan(command, ["install"], { cwd: `./${project}` });

  // 运行项目
  console.log("正在启动项目,请稍后...");
  commandSpan(command, ["run", "serve"], { cwd: `./${project}` });

  // 打开浏览器
  open("http://localhost:8080/");
};

/**
 * 创建组件
 * @param {String} name 组件名称
 * @param {String} dest 组件目录
 */
const addComponentAction = async (name, dest) => {
  // 编译模板
  const rusult = await compile("../templates/vue/component.ejs", {
    name: name,
    lowerName: name.toLowerCase(),
  });

  // 写入文件
  const targetPath = path.resolve(dest, `${name}.vue`);
  writeToFile(targetPath, rusult);

  console.log(`组件"${name}"创建完成，保存在 ${targetPath}`);
};

/**
 * 创建页面
 * @param {String} name 页面名称
 * @param {String} dest 页面目录
 */
const addPageAction = async (name, dest) => {
  // 编译模板
  const data = {
    name: name,
    lowerName: name.toLowerCase(),
  };
  const pageRusult = await compile("../templates/vue/component.ejs", data);
  const routerRusult = await compile("../templates/vue/router.ejs", data);

  // 写入文件
  const targetDest = path.resolve(dest, name.toLowerCase());

  const targetRouterPath = path.resolve(targetDest, `router.vue`);
  const targetPagePath = path.resolve(targetDest, `${name}.vue`);

  if (createDirSync(targetDest)) {
    writeToFile(targetPagePath, pageRusult);
    writeToFile(targetRouterPath, routerRusult);
  }

  console.log(`页面"${name}"创建完成，保存在 ${targetPagePath}`);
};

/**
 * 创建 Store
 * @param {String} name Store名称
 * @param {String} dest 页面目录
 */
const addStoreAction = async (name, dest) => {
  // 编译模板
  const storeRusult = await compile("../templates/vue/store.ejs", {});
  const storeTypeRusult = await compile("../templates/vue/store-type.ejs", {});

  // 写入文件
  const targetDest = path.resolve(dest, name.toLowerCase());

  const storeRouterPath = path.resolve(targetDest, `${name}.js`);
  const storeTypePagePath = path.resolve(targetDest, `type.js`);
  if (createDirSync(targetDest)) {
    writeToFile(storeRouterPath, storeRusult);
    writeToFile(storeTypePagePath, storeTypeRusult);
  }
  console.log(`Store"${name}"创建完成，保存在 ${targetDest}`);
};

module.exports = {
  createProjectAction,
  addComponentAction,
  addPageAction,
  addStoreAction,
};
